
package com.kaoshi.jeeweb.common.web.base;

import com.kaoshi.jeeweb.common.config.Global;
import com.kaoshi.jeeweb.common.persistence.DataEntity;
import com.kaoshi.jeeweb.common.service.base.BaseGenericService;
import com.kaoshi.jeeweb.common.web.argument.annotation.SearchConditionDefaults;
import com.kaoshi.jeeweb.common.web.argument.search.SearchCondition;
import com.kaoshi.jeeweb.common.web.permission.PermissionList;
import com.kaoshi.myweb.common.lib.pagehelper.PageInfo;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * 基础CRUD 控制器，基础的增删改查基类
 * <p>User: Zhang Kaitao
 * <p>Date: 13-2-23 下午1:20
 * <p>Version: 1.0
 */
public abstract class BaseCRUDController<M extends DataEntity, ID extends Serializable>
        extends BaseGenericController<M, ID>{

    protected BaseGenericService<M, ID> genericService;

    private boolean listAlsoSetCommonData = false;

    protected PermissionList permissionList = null;

    /**
     * 设置基础service
     *
     * @param genericService
     */
//    @Autowired
    public void setGenericService(BaseGenericService<M, ID> genericService) {
        this.genericService = genericService;
    }

    /**
     * 列表也设置common data
     */
    public void setListAlsoSetCommonData(boolean listAlsoSetCommonData) {
        this.listAlsoSetCommonData = listAlsoSetCommonData;
    }

    /**
     * 权限前缀：如sys:user
     * 则生成的新增权限为 sys:user:create
     */
    public void setResourceIdentity(String resourceIdentity) {
        if (!StringUtils.isEmpty(resourceIdentity)) {
            permissionList = PermissionList.newPermissionList(resourceIdentity);
        }
    }

    @RequestMapping(value = "list")
    @SearchConditionDefaults(sort = "id=desc")
    public String list(SearchCondition searchCondition, Model model) {

        if (permissionList != null) {
            this.permissionList.assertHasViewPermission();
        }
        PageInfo<M> page = genericService.queryByPage(searchCondition);
        model.addAttribute("page", page);
        if (listAlsoSetCommonData) {
            setCommonData(model);
        }
        return viewName("List");
    }

    /**
     * 仅返回表格数据
     *
     * @param model
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, headers = "table=true")
    @SearchConditionDefaults(sort = "id=desc")
    public String listTable(SearchCondition searchCondition, Model model) {
        list(searchCondition , model);
        return viewName("Table");
    }


    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String view(Model model, @PathVariable("id") ID id) {

        if (permissionList != null) {
            this.permissionList.assertHasViewPermission();
        }

        M m = genericService.queryById(id);
        setCommonData(model);
        model.addAttribute("m", m);
        model.addAttribute(Global.OP_NAME, "查看");
        return viewName("Form");
    }

    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String showCreateForm(Model model, HttpServletRequest request) {

        if (permissionList != null) {
            this.permissionList.assertHasCreatePermission();
        }


        setCommonData(model);
        model.addAttribute(Global.OP_NAME, "新增");
        if (!model.containsAttribute("m")) {
            model.addAttribute("m", newModel());
        }
        model.addAttribute("action", request.getRequestURI());
        return viewName("Form");
    }


    @RequestMapping(value = "create", method = RequestMethod.POST)
    public String create( Model model, @ModelAttribute("m") M m, String backUrl,
            RedirectAttributes redirectAttributes, HttpServletRequest request) {

        if (permissionList != null) {
            this.permissionList.assertHasCreatePermission();
        }

//        if (hasError(m, result)) {
//            return showCreateForm(model);
//        }

        if (!beanValidator(model, m)){
            return showCreateForm(model, request);
        }
        m.setDelFlag("0");
        genericService.insert(m);
        //redirectAttributes.addFlashAttribute(Global.MESSAGE, "新增成功");
        addMessage(redirectAttributes, "新增成功");
        //return "redirect:" + adminPath + "/sample/search/?repage";
        return "redirect:" + backUrl;
    }


    @RequestMapping(value = "{id}/update", method = RequestMethod.GET)
    public String showUpdateForm(@PathVariable("id") ID id, Model model) {

        if (permissionList != null) {
            this.permissionList.assertHasUpdatePermission();
        }

        M m = genericService.queryById(id);
        setCommonData(model);

        setCommonData(model);
        model.addAttribute(Global.OP_NAME, "修改");
        model.addAttribute("m", m);
        return viewName("Form");
    }

    @RequestMapping(value = "{id}/update", method = RequestMethod.POST)
    public String update( @ModelAttribute("m") M m,  String backUrl,
            @RequestParam(value = Global.BACK_URL, required = false) String backURL,
            RedirectAttributes redirectAttributes) {

        if (permissionList != null) {
            this.permissionList.assertHasUpdatePermission();
        }

//        if (hasError(m, result)) {
//            return showUpdateForm(m, model);
//        }
        genericService.updateByPrimaryKey(m);
        //redirectAttributes.addFlashAttribute(Global.MESSAGE, "修改成功");
        addMessage(redirectAttributes, "修改成功");
        //return "redirect:" + adminPath + "/sample/search/?repage";
        return "redirect:" + backUrl;
    }

    @RequestMapping(value = "{id}/delete", method = RequestMethod.GET)
    public String showDeleteForm(@PathVariable("id") ID id,String backUrl, Model model, RedirectAttributes redirectAttributes) {

        if (permissionList != null) {
            this.permissionList.assertHasDeletePermission();
        }

        //setCommonData(model);
        //model.addAttribute(Global.OP_NAME, "删除");
        genericService.deleteByPrimaryKey(id);
        addMessage(redirectAttributes, "删除成功");
        //model.addAttribute("m", m);

        return "redirect:" + backUrl;
    }

//    @RequestMapping(value = "{id}/delete", method = RequestMethod.POST)
//    public String delete(
//            @PathVariable("id") M m,
//            @RequestParam(value = Global.BACK_URL, required = false) String backURL,
//            RedirectAttributes redirectAttributes) {


//        if (permissionList != null) {
//            this.permissionList.assertHasDeletePermission();
//        }



//        redirectAttributes.addFlashAttribute(Global.MESSAGE, "删除成功");
//        return "redirect:" + adminPath + "/sample/search/?repage";
//    }

    @RequestMapping(value = "batch/delete", method = {RequestMethod.GET, RequestMethod.POST})
    public String deleteInBatch(
            @RequestParam(value = "ids", required = false) ID[] ids,
            @RequestParam(value = Global.BACK_URL, required = false) String backURL,
            RedirectAttributes redirectAttributes) {


//        if (permissionList != null) {
//            this.permissionList.assertHasDeletePermission();
//        }

    	//批量刪除
        //baseService.delete(ids);

        redirectAttributes.addFlashAttribute(Global.MESSAGE, "删除成功");
        return redirectToUrl(backURL);
    }

}
